package cn.andios.service;

import cn.andios.pojo.Stu;
import cn.andios.pojo.Tea;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @description:分配登录用户的权限
 * @author:LSD
 * @when:2019/1/25/12:42
 */
public class UserDetailsServiceImpl implements UserDetailsService {

    private static final Logger logger=LogManager.getLogger(UserDetailsServiceImpl.class);

    @Autowired
    private  StuService stuService;
    @Autowired
    private TeaService teaService;

    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        UserDetails userDetails= null;
        try {
            //根据用户名查找教师和学生，如果是tea，那么stu就为null
            Tea tea = teaService.findTeaById(username);
            Stu stu = stuService.findStuById(username);

            System.out.println("LoggerAuthority:username:" + username);
            List<GrantedAuthority> authList= new ArrayList<GrantedAuthority>();

            //根据用户名查找到的是教师
            if(tea != null){
                System.out.println("LoggerAuthority:" +tea.toString());
                authList.clear();
                authList.add(new SimpleGrantedAuthority("ROLE_TEA"));
                return new User(username,tea.getTeaPwd(),authList);
             //根据用户名查找到的是学生
            }else if(stu != null){
                System.out.println("LoggerAuthority:" + stu.toString());
                authList.clear();
                authList.add(new SimpleGrantedAuthority("ROLE_STU"));
                return new User(username,stu.getStuPwd(),authList);
            }else {
                return null;
            }
        } catch (Exception e){
            e.printStackTrace();
        }
            return null;
    }
}
